package com.andy.eqm.server.entity;

import java.util.Map;
import java.util.Map.Entry;

import org.apache.commons.lang3.StringUtils;

import com.google.common.collect.Maps;
import com.google.common.util.concurrent.AtomicLongMap;

public class UsrGameInfo extends BaseEntity{

	private static final long serialVersionUID = 1L;

	public UsrGameInfo() {
	}
	
	public UsrGameInfo(Long id) {
		super(id);
	}
	
	private Long uid;
	private Long coin;
	private Long lastGiftTime;
	private String bag;

	public Long getUid() {
		return uid;
	}

	public void setUid(Long uid) {
		this.uid = uid;
	}

	public Long getCoin() {
		return coin;
	}

	public void setCoin(Long coin) {
		this.coin = coin;
	}

	public int addCoin(int coin){
		if(this.coin == null){
			this.coin = 0L;
		}
		Long old = this.coin;
		this.coin += coin;
		if(this.coin < 0)this.coin = 0L;
		return (int) (this.coin - old);
	}

	public static String table() {
		return "usr_game_info";
	}

	public String getBag() {
		if(items != null){
			StringBuilder sb = new StringBuilder();
			for(Entry<Integer, Long> entry:items.asMap().entrySet()){
				sb.append(entry.getKey()).append("=").append(entry.getValue()).append(",");
			}
			if(sb.length() > 0){
				bag = sb.substring(0, sb.length()-1);
			}else{
				bag = "";
			}
		}
		return bag;
	}

	public void setBag(String bag) {
		this.bag = bag;
		if(StringUtils.isNotBlank(bag)){
			String[] itemstr = bag.split(",");
			Map<Integer,Long> itemsT = Maps.newHashMap();
			for(String istr:itemstr){
				String[] ite = istr.split("=");
				itemsT.put(Integer.valueOf(ite[0]), Long.valueOf(ite[1]));
			}
			items = AtomicLongMap.create(itemsT);
		}
	}
	
	private AtomicLongMap<Integer> items = AtomicLongMap.create();
	public void addItem(int itemId, int size){
		items.addAndGet(itemId, size);
		setLastGiftTime(System.currentTimeMillis()/1000);
	}
	
	public Map<Integer, Long> items() {
		return items.asMap();
	}
	
	public Long item(int itemId) {
		return items.get(itemId);
	}

	public Long getLastGiftTime() {
		return lastGiftTime;
	}

	public void setLastGiftTime(Long lastGiftTime) {
		this.lastGiftTime = lastGiftTime;
	}

	
}
